<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { getApi, createApi } from "@/api/dailyDetail"
import { Search, Refresh, RefreshRight } from "@element-plus/icons-vue"
import { type FormInstance } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import dayjs from "dayjs"
import { toFixed } from "@/utils"

defineOptions({
  // 命名当前组件
  name: "DailyDetail"
})
const searchData = reactive({
  order_number: "",
  store_name: "",
  data_date: "",
  product_id: ""
})
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const tableData = ref<any[]>([])

const params = reactive({
  data_date: "",
  store_name: ""
})

const getTableData = () => {
  loading.value = true
  if (searchData.data_date) {
    searchData.data_date = dayjs(searchData.data_date).format("YYYY-MM-DD")
  }
  getApi({
    page: paginationData.page,
    size: paginationData.size,
    ...searchData
    // data_date: params.data_date
  })
    .then(({ data }: any) => {
      paginationData.total = data.pagination.total
      tableData.value = data.list
      console.log(data.list)
    })
    .catch((e) => {
      tableData.value = []
      console.log(e)
    })
    .finally(() => {
      loading.value = false
    })
}

//#endregion

/** 监听分页参数的变化 */
watch([() => paginationData.page, () => paginationData.size], getTableData, { immediate: true })

const formRules = {
  store_name: [{ required: true, trigger: "blur", message: "请输入店铺名称" }],
  data_date: [{ required: true, trigger: "blur", message: "请选择数据日期" }]
}
const formRef = ref()
const submit = async () => {
  formRef.value
    ?.validate(async (valid: boolean, fields: any) => {
      if (!valid) return console.error("表单校验不通过", fields)
      loading.value = true

      try {
        await createApi({
          data_date: dayjs(params.data_date).format("YYYY-MM-DD"),
          store_name: params.store_name
        })
        getTableData()
      } catch (e) {
        console.log(e)
      }
    })
    .finally(() => {
      loading.value = false
    })
}
const searchFormRef = ref<FormInstance | null>(null)

const handleSearch = () => {
  paginationData.page === 1 ? getTableData() : (paginationData.page = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-collapse accordion>
        <el-collapse-item name="1">
          <template #title>导入数据</template>
          <div>
            <el-form ref="formRef" :model="params" :rules="formRules">
              <el-form-item prop="store_name" label="店铺名称" required>
                <el-input v-model="params.store_name" placeholder="请输入" style="width: 400px" />
              </el-form-item>
              <el-form-item prop="data_date" label="数据日期" required>
                <el-date-picker v-model="params.data_date" placeholder="请选择" style="width: 400px" />
              </el-form-item>
              <el-form-item>
                <el-button @click="submit" type="primary">生成日表</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="order_number" label="订单编号">
          <el-input v-model="searchData.order_number" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="product_id" label="商品ID">
          <el-input v-model="searchData.product_id" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="store_name" label="店铺名称">
          <el-input v-model="searchData.store_name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="data_date" label="数据日期">
          <el-date-picker v-model="searchData.data_date" placeholder="请选择" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="order_number" label="订单编号" fixed width="180" />
          <el-table-column prop="product_info" label="商品信息" fixed width="240">
            <template #default="scope">
              <div v-for="item in JSON.parse(scope.row.product_info)" :key="item.product_id">
                <div>商品ID: {{ item.product_id }}</div>
                <div>商品编码: {{ item.product_code }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="product_cost" label="成本">
            <template #default="scope">
              {{ toFixed(scope.row.product_cost) }}
            </template>
          </el-table-column>
          <el-table-column prop="payment_cost" label="打款成本">
            <template #default="scope">
              {{ toFixed(scope.row.payment_cost) }}
            </template>
          </el-table-column>
          <el-table-column prop="platform_service_fee" label="平台服务费">
            <template #default="scope">
              {{ toFixed(scope.row.platform_service_fee) }}
            </template>
          </el-table-column>
          <el-table-column prop="commission" label="达人佣金">
            <template #default="scope">
              {{ toFixed(scope.row.commission) }}
            </template>
          </el-table-column>
          <el-table-column prop="service_fee" label="团长服务费">
            <template #default="scope">
              {{ toFixed(scope.row.service_fee) }}
            </template>
          </el-table-column>
          <el-table-column prop="erp_cost" label="运费">
            <template #default="scope">
              {{ toFixed(scope.row.erp_cost) }}
            </template>
          </el-table-column>
          <el-table-column prop="order_payable_amount" label="订单应付金额">
            <template #default="scope">
              {{ toFixed(scope.row.order_payable_amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_platform_discount" label="平台实际承担优惠金额">
            <template #default="scope">
              {{ toFixed(scope.row.actual_platform_discount) }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_discount_amount_by_merchant" label="商家实际承担优惠金额">
            <template #default="scope">
              {{ toFixed(scope.row.actual_discount_amount_by_merchant) }}
            </template>
          </el-table-column>
          <el-table-column prop="actual_discounts_for_influencer" label="达人实际优惠">
            <template #default="scope">
              {{ toFixed(scope.row.actual_discounts_for_influencer) }}
            </template>
          </el-table-column>
          <el-table-column prop="extra_cost" label="费用">
            <template #default="scope">
              {{ toFixed(scope.row.extra_cost) }}
            </template>
          </el-table-column>
          <el-table-column prop="rebate" label="返利">
            <template #default="scope">
              {{ toFixed(scope.row.rebate) }}
            </template>
          </el-table-column>
          <el-table-column prop="profit" label="利润">
            <template #default="scope">
              {{ toFixed(scope.row.profit) }}
            </template>
          </el-table-column>
          <el-table-column prop="store_name" label="店铺名称" />
          <el-table-column prop="data_date" label="数据日期" fixed="right" width="120">
            <template #default="scope">
              {{ dayjs(scope.row.data_date).format("YYYY-MM-DD") }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.size"
          :currentPage="paginationData.page"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
